package com.leyou.item.web;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.service.BrandService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("brand")
public class BrandController {

    private final BrandService brandService;

    public BrandController(BrandService brandService) {
        this.brandService = brandService;
    }

    /**
     * 根据id查询品牌
     * @param id 品牌id
     * @return 品牌对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> queryBrandById(@PathVariable("id") Long id){
        Brand brand = brandService.getById(id);
        if (brand == null) {
            // 404
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(new BrandDTO(brand));
    }

    /**
     * 根据id集合查询品牌
     * @param ids id集合
     * @return 品牌集合
     */
    @GetMapping("list")
    public ResponseEntity<List<BrandDTO>> queryBrandByIds(@RequestParam("ids") List<Long> ids){
        return ResponseEntity.ok(BrandDTO.convertEntityList(brandService.listByIds(ids)));
    }

    /**
     * 分页查询品牌
     * @param key 关键字
     * @param page 当前页码
     * @param rows 每页大小
     * @return 品牌分页结果
     */
    @GetMapping("page")
    public ResponseEntity<PageDTO<BrandDTO>> queryBrandByPage(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows
    ){
        PageDTO<BrandDTO> result = brandService.queryBrandByPage(key, page, rows);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据分类id查询品牌集合
     * @param id 分类id
     * @return 品牌集合
     */
    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandByCategory(@RequestParam("id") Long id){
        List<BrandDTO> list = brandService.queryBrandByCategoryId(id);
        return ResponseEntity.ok(list);
    }

    /**
     * 新增品牌
     * @param brandDTO 品牌参数
     * @return 无
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(BrandDTO brandDTO){
        // 新增品牌和中间表
        brandService.saveBrand(brandDTO);
        // 新增成功，一般返回201
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

}
